﻿using AutoMapper;
using System;
using System.Linq;

namespace Joy.Erp.BasicArchives.Core
{
    public static class AutoMapperExtensions
    {
        public static IMappingExpression<TSource, TDestination> MapChildren<TSource, TDestination, TChildSource, TChildDestination>(this IMappingExpression<TSource, TDestination> mappingExpression)
            where TSource : IHasChildren<TChildSource>
            where TDestination : IHasChildren<TChildDestination>
            where TChildSource : IChildDto
            where TChildDestination : IChild
        {
            return mappingExpression
                .ForMember(src => src.Children, opt => opt.Ignore())
                .AfterMap((src, dest, context) =>
                {
                    // 删除逻辑：删除在源数据中不存在的子实体
                    var childrenToRemove = dest.Children.Where(destChild =>
                        !src.Children.Any(srcChild => srcChild.Id.HasValue && srcChild.Id.Value == destChild.Id)).ToList();
                    foreach (var child in childrenToRemove)
                    {
                        dest.Children.Remove(child);
                    }

                    // 更新和新增逻辑
                    foreach (var srcChild in src.Children)
                    {
                        var existingChild = srcChild.Id.HasValue && srcChild.Id.Value != Guid.Empty
                            ? dest.Children.FirstOrDefault(destItem => destItem.Id == srcChild.Id.Value)
                            : default;

                        if (existingChild != null)
                        {
                            context.Mapper.Map(srcChild, existingChild);
                        }
                        else
                        {
                            var newChild = context.Mapper.Map<TChildDestination>(srcChild);
                            dest.Children.Add(newChild);
                        }
                    }
                });
        }
    }
}
